package com.aiton.bamin.bamindaijiadrier.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.HTTPUtils;
import com.aiton.administrator.shane_library.shane.utils.IsMobileNOorPassword;
import com.aiton.administrator.shane_library.shane.utils.VolleyListener;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.Sms;
import com.aiton.bamin.bamindaijiadrier.model.VersionAndHouTaiIsCanUse;
import com.aiton.bamin.bamindaijiadrier.model.Wallet;
import com.aiton.bamin.bamindaijiadrier.widget.OnPasswordInputFinish;
import com.aiton.bamin.bamindaijiadrier.widget.PasswordView;
import com.android.volley.VolleyError;
import com.blankj.utilcode.utils.EncryptUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.HashMap;
import java.util.Map;

import cz.msebera.android.httpclient.Header;

public class ChangePasswordActivity extends ZjbBaseActivity implements View.OnClickListener {
    private static final String TAG = "ChangePasswordActivity";
    private EditText mEdt_phone;
    private EditText mEdt_sms;
    private EditText mEdt_IDcard;
    private EditText mEdt_new_password;
    private Button mBtn_sendSms;
    private Button mBtn_sure;
    private String mPhone;
    private int[] mI;
    private Runnable mR;
    private String mSuijiMath;
    private EditText mEdt_new_password_again;
    private String changePassword;
    private String mType;
    private Wallet.DatasBean mWallet;
    private View mLine_set_password;
    private View mLine_set_password_again;
    private PopEnterPassword mPopEnterPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);
        init();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initViews() {
        if (TextUtils.equals(mType, Constant.TYPE.WALLET)) {
            mEdt_phone.setText(mWallet.getDriverPhone());
            mEdt_phone.setFocusableInTouchMode(false);
            mBtn_sure.setText("重设密码");
            mLine_set_password.setVisibility(View.GONE);
            mLine_set_password_again.setVisibility(View.GONE);
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                    != PackageManager.PERMISSION_GRANTED) {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},
                        Constant.PERMISSION.PERMISSION_READ_SMS);
            } else {
                sendSMS();
            }
        }
    }

    @Override
    protected void setListeners() {

        mBtn_sendSms.setOnClickListener(this);
        mBtn_sure.setOnClickListener(this);
        findViewById(R.id.imageView_back).setOnClickListener(this);
    }


    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mType = intent.getStringExtra(Constant.INTENT_KEY.TYPE);
        if (TextUtils.equals(mType, Constant.TYPE.WALLET)) {
            mWallet = (Wallet.DatasBean) intent.getSerializableExtra(Constant.INTENT_KEY.WALLET);
        }
    }

    @Override
    protected void findID() {
        mEdt_phone = (EditText) findViewById(R.id.edt_phone);
        mEdt_sms = (EditText) findViewById(R.id.edt_sms);
        mEdt_IDcard = (EditText) findViewById(R.id.edt_IDcard);
        mEdt_new_password = (EditText) findViewById(R.id.edt_new_password);
        mBtn_sendSms = (Button) findViewById(R.id.btn_sendSms);
        mBtn_sure = (Button) findViewById(R.id.btn_sure);
        mEdt_new_password_again = (EditText) findViewById(R.id.edt_new_password_again);
        mLine_set_password = findViewById(R.id.line_set_password);
        mLine_set_password_again = findViewById(R.id.line_set_password_again);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.btn_sendSms:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},
                            Constant.PERMISSION.PERMISSION_READ_SMS);
                } else {
                    if (IsMobileNOorPassword.isMobileNO(mEdt_phone.getText().toString().trim())) {
                        sendSMS();
                    } else {
                        mEdt_phone.setError("输入手机格式错误");
                    }
                }
                break;
            case R.id.btn_sure:
                if (!IsMobileNOorPassword.isMobileNO(mEdt_phone.getText().toString().trim())) {
                    mEdt_phone.setError("请输入正确的手机号");
                } else if (TextUtils.isEmpty(mEdt_sms.getText().toString())) {
                    mEdt_sms.setError("验证码不能为空");
                } else if (!(mEdt_IDcard.getText().length() == 15 || mEdt_IDcard.getText().length() == 18)) {
                    mEdt_IDcard.setError("请输入正确的身份证号");
                } else if (TextUtils.equals(mType, Constant.TYPE.WALLET)) {
                    showChangePassword();
                } else if (!IsMobileNOorPassword.isPassword(mEdt_new_password.getText().toString().trim())) {
                    mEdt_new_password.setError("密码必须大于等于6位，且由字母及数字组合");
                } else if (!mEdt_new_password_again.getText().toString().trim().equals(mEdt_new_password.getText().toString().trim())) {
                    mEdt_new_password_again.setError("两次输入密码不一样");
                } else if (TextUtils.equals(mType, Constant.TYPE.LOGIN)) {
                    sureChange();
                }
                break;
        }
    }

    private void showChangePassword() {

        View view = getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        mPopEnterPassword = new PopEnterPassword(ChangePasswordActivity.this, "设置", "请输入密码");

        // 显示窗口
        mPopEnterPassword.showAtLocation(ChangePasswordActivity.this.findViewById(R.id.activity_change_password),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
    }
    /**
     * 输入支付密码
     *
     * @author lining
     */
    public class PopEnterPassword extends PopupWindow {

        private PasswordView pwdView;

        private View mMenuView;

        private Activity mContext;


        public PopEnterPassword(final Activity context, String way, String money) {

            super(context);

            this.mContext = context;

            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            mMenuView = inflater.inflate(R.layout.pop_enter_password, null);

            pwdView = (PasswordView) mMenuView.findViewById(R.id.pwd_view);

            TextView mTv_way = (TextView) mMenuView.findViewById(R.id.tv_way);
            TextView mTv_forget_password = (TextView) mMenuView.findViewById(R.id.tv_forget_password);
            final TextView mTv_money = (TextView) mMenuView.findViewById(R.id.tv_money);

            mTv_way.setText(way);
            mTv_money.setText(money);
            mTv_forget_password.setVisibility(View.GONE);

            //添加密码输入完成的响应
            pwdView.setOnFinishInput(new OnPasswordInputFinish() {

                @Override
                public void notTheSame(String password) {
                    mTv_money.setTextSize(20);
                    mTv_money.setText("两次输入密码不一致,请重新输入");
                }

                @Override
                public void theSamePassword(String password) {
                    changeWalletPassword(password);
                    dismiss();
                }

                @Override
                public void inputAgain(String password) {
                    mTv_money.setText("再次输入密码");


                }
            });


            // 监听X关闭按钮
            pwdView.getImgCancel().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            // 监听键盘上方的返回
            pwdView.getVirtualKeyboardView().getLayoutBack().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            // 设置SelectPicPopupWindow的View
            this.setContentView(mMenuView);
            // 设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            // 设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            // 设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
            // 设置SelectPicPopupWindow弹出窗体动画效果
            this.setAnimationStyle(R.style.pop_add_ainm);
            // 实例化一个ColorDrawable颜色为半透明
            ColorDrawable dw = new ColorDrawable(0x66000000);
            // 设置SelectPicPopupWindow弹出窗体的背景
            this.setBackgroundDrawable(dw);

        }
    }
    /**
     * 改变钱包密码
     * @param password
     */
    private void changeWalletPassword(String password) {
        showLoadingDialog();
        String password4Encrypt = EncryptUtils.encryptSHA256ToString(password);

        String url = Constant.Url.CHANGE_NOTECASE_PASSWORD;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("driverId",mWallet.getDriverId());
        params.put("cardId",mEdt_IDcard.getText().toString().trim());
        params.put("newPassword",password4Encrypt);
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e(TAG, "更改支付密码: --->>" + s);
                try {
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    if(sms.getStatus() == 0){
                        showSuccessDialog(sms.getMes());
//                        Toast.makeText(ChangePasswordActivity.this, sms.getMes(), Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(ChangePasswordActivity.this, sms.getMes(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(ChangePasswordActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
                }
                cancelLoadingDialog();
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(ChangePasswordActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                cancelLoadingDialog();
            }
        });
    }

    private void sureChange() {
        if (TextUtils.equals(mSuijiMath, mEdt_sms.getText().toString())) {
            String password = mEdt_new_password.getText().toString().trim();
            String password4Encrypt = EncryptUtils.encryptSHA256ToString(password);
            String url = Constant.Url.CHANGE_PASSWORD;
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            params.put("phone", mEdt_phone.getText().toString().trim());
            params.put("cardId", mEdt_IDcard.getText().toString().trim());
            params.put("password", password4Encrypt);
            asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    String s = new String(responseBody);
                    Log.e("ChangePasswordActivity", "onSuccess: --->>" + s);
                    String str = "";
                    try {
                        VersionAndHouTaiIsCanUse versionAndHouTaiIsCanUse = GsonUtils.parseJSON(s, VersionAndHouTaiIsCanUse.class);

                        if (versionAndHouTaiIsCanUse.getStatus() == 2) {//更改成功
                            str = versionAndHouTaiIsCanUse.getMes();

                            finishTo();
                        } else if (versionAndHouTaiIsCanUse.getStatus() == 1) {//更改失败
                            str = versionAndHouTaiIsCanUse.getMes();

                        }
                        Toast.makeText(ChangePasswordActivity.this, str, Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Toast.makeText(ChangePasswordActivity.this, "修改密码失败", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Toast.makeText(ChangePasswordActivity.this, "短信验证失败", Toast.LENGTH_SHORT).show();
        }
    }
    private void showSuccessDialog(String title) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, title, "确定");
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                finishTo();
                singleBtnDialog.dismiss();
            }
        });
        singleBtnDialog.show();
    }
    private void sendSMS() {
        mBtn_sendSms.removeCallbacks(mR);

        mPhone = mEdt_phone.getText().toString().trim();
        boolean mobileNO = IsMobileNOorPassword.isMobileNO(mPhone);
        if (mobileNO) {
            mBtn_sendSms.setEnabled(false);
            mI = new int[]{60};
            mR = new Runnable() {
                @Override
                public void run() {
                    mBtn_sendSms.setText((mI[0]--) + "秒后重发");
                    if (mI[0] == 0) {
                        mBtn_sendSms.setEnabled(true);
                        mBtn_sendSms.setText("获取验证码");
                        return;
                    } else {

                    }
                    mBtn_sendSms.postDelayed(mR, 1000);
                }
            };
            mBtn_sendSms.postDelayed(mR, 0);
            getSms();
        } else {
            Toast.makeText(this, "输入的手机格式有误", Toast.LENGTH_SHORT).show();
            mEdt_phone.setText("");
        }
    }

    private void getSms() {
        mSuijiMath = (int) (Math.random() * 9000 + 1000) + "";
        String url = Constant.Url.GET_SMS;
        Map<String, String> map = new HashMap<>();
        map.put("phone", mEdt_phone.getText().toString().trim());
        map.put("code", mSuijiMath + "");
        HTTPUtils.post(this, url, map, new VolleyListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.showShortToast(ChangePasswordActivity.this, "短信发送失败");
                mBtn_sendSms.setEnabled(true);
                mBtn_sendSms.setText("获取验证码");
                mBtn_sendSms.removeCallbacks(mR);

            }

            @Override
            public void onResponse(String s) {
                try {
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    int status = sms.getStatus();
                    Toast.makeText(ChangePasswordActivity.this, sms.getMes(), Toast.LENGTH_SHORT).show();
                    if (status == 0) {
                        //短信发送成功
                    } else if (status == 1) {
                        //短信发送失败
                    }
                } catch (Exception e) {
                    Toast.makeText(ChangePasswordActivity.this, "服务器出错", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
